package com.link.play.fit.ai.ad

import android.app.Activity
import android.content.Context
import android.util.Log
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.appopen.AppOpenAd
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.ad.AdmobHelper.isAdmobInit

object AdmobOpen {

    private val TAG = "AdmobOpen"
    private var currentAd: AppOpenAd? = null

    fun show(activity: Activity, showCallBack: AdsShowCallBack? = null) {

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

//        if (!isAdmobInit) {
//            showCallBack?.failed()
//            return
//        }

        if (currentAd != null) {
            showReadyAd(activity, showCallBack)
        } else {
            loadAd(activity) { ad ->
                if (ad == null) {
                    showCallBack?.failed()
                } else {
                    showReadyAd(activity, showCallBack)
                }
            }
        }
    }


    fun loadAd(context: Context, loadCallBack: (appOpenAd: AppOpenAd?) -> Unit) {

        AppOpenAd.load(
            context,
            GlobalConfig.ID_ADMOB_OPEN,
            AdRequest.Builder().build(),
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(appOpenAd: AppOpenAd) {
                    currentAd = appOpenAd
                    loadCallBack.invoke(appOpenAd)
                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    Log.e(TAG, "loadAdError=${loadAdError.code} ${loadAdError.message}")
                    loadCallBack.invoke(null)
                }
            }
        )
    }


    private fun showReadyAd(activity: Activity, showCallBack: AdsShowCallBack?) {

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {
                    currentAd = null
                    showCallBack?.show()
                }

                override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                    Log.e(TAG, "adError=${adError.message} ${adError.code}")
                    showCallBack?.failed()
                }

                override fun onAdDismissedFullScreenContent() {
                    showCallBack?.close()
                }

                override fun onAdClicked() {
                }
            }
            show(activity)
        }
    }
}